package ldh.im.fxbase.util;

import ldh.im.dto.business.item.FileItem;
import ldh.im.dto.business.message.MessageObject;
import ldh.im.dto.enums.MessageType;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.MessageExt;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;

public class MessageUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageUtil.class);

    public static MessageObject toMessageObject(ImMessage imMessage) {
        MessageObject message = new MessageObject<>();
        message.setMessageType(imMessage.getMessageType());
        message.setLocalSeq(imMessage.getClientId());
        message.setBean(MessageUtil.buildContent(imMessage));
        message.setToUserId(imMessage.getToUserId());
        message.setGroupCode(imMessage.getGroupCode());
        message.setFromUserId(imMessage.getFromUserId());
        if (imMessage.getRefType() != null) {
            message.setRefMessageIds(imMessage.getRefMessageIds());
            message.setRefType(imMessage.getRefType().toMessageRefType());
        }
        return message;
    }

    public static Object buildContent(ImMessage imMessage) {
        if (imMessage.getMessageType() == MessageType.Text || imMessage.getMessageType() == MessageType.Html
                || imMessage.getMessageType() == MessageType.RichText || imMessage.getMessageType() == MessageType.Web
                || imMessage.getMessageType() == MessageType.Url || imMessage.getMessageType() == MessageType.Chat) {
            return imMessage.getContent();
        } else if (imMessage.getMessageType().isFile()) {
            FileItem fileItem = new FileItem();
            MessageExt messageExt = imMessage.getMessageExt();
            if (messageExt != null && messageExt.getFileName() != null) {
                fileItem.setFileName(messageExt.getFileName());
                fileItem.setFileUrl(imMessage.getContent());
                fileItem.setSize(messageExt.getSize());
                fileItem.setMd5(messageExt.getMd5());
                fileItem.setTime(messageExt.getTime() == null ? 0 : messageExt.getTime());
                fileItem.setOriginalName(messageExt.getOriginalName());
                fileItem.setImageWidth(messageExt.getImageWidth());
                fileItem.setImageHeight(messageExt.getImageHeight());
            } else {
                File file = new File(imMessage.getContent());
                fileItem.setSize(getFileSize(file));
                fileItem.setFileUrl(imMessage.getContent());
                fileItem.setFileName(file.getName());
                fileItem.setOriginalName(file.getName());
                fileItem.setTime(0);

                fileItem.setMd5(getFileSha512(file));
                int[] size = FileUtil.getImageSize(file);
                if (size != null) {
                    fileItem.setImageWidth(size[0]);
                    fileItem.setImageHeight(size[1]);
                }
            }

            return fileItem;
        } else {
            throw new RuntimeException("不支持这种模式" + imMessage.getMessageType());
        }
    }

    public static String buildLastedMessage(MessageType messageType, String content) {
        if (messageType.isFile()) {
            if (messageType == MessageType.Image) {
                return "[图片]";
            } else if (messageType == MessageType.File) {
                return "[文件]";
            } else if (messageType == MessageType.Audio) {
                return "[音频]";
            } else if (messageType == MessageType.Video) {
                return "[视频]";
            } else {
                LOGGER.error("不支持这种类型: {}", messageType.name());
            }
        } else {
            int length = ParamUtil.MESSAGE_SESSION_LATELY_MESSAGE_LENGTH;
            boolean isLongStr = StringUtil.stringBytesLength(content) > length;
            String latelyMessage = content;
            while (isLongStr) {
                length = length - 4;
                latelyMessage = StringUtil.subString(latelyMessage, length);
                isLongStr = StringUtil.stringBytesLength(latelyMessage) > length;
            }
            if(isLongStr) latelyMessage += "...";
            return latelyMessage;
        }
        return "";
    }

    private static long getFileSize(File file) {
        try {
           return Files.size(file.toPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getFileSha512(File file) {
        try(InputStream inputStream = new FileInputStream(file)) {
            String md5 = DigestUtils.sha512Hex(inputStream);
            return md5;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
